package com.dm.library.utils;

import android.content.Context;
import android.graphics.Typeface;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextSwitcher;
import android.widget.TextView;

/**
 * 设置字体的工具类
 *
 * @author jiaohongyun
 * @date 2015年8月7日
 */
public class FontTypefaceHelper {
    /**
     * 字体文件位置，如果为null则使用系统默认字体
     * 字体文件要放到assets/fonts目录下面
     */
    private static String FONT_NAME = "yejing.ttf";

    private static Typeface typeface;

    public static void applyFont(final Context context, final View root) {
        applyFont(context, root, null);
    }

    /**
     * 设置字体
     *
     * @param context
     * @param root     需要使用特殊字体的最上层控件
     * @param fontName 字体名称
     */
    public static void applyFont(final Context context, final View root, String fontName) {
        if (FONT_NAME == null) {
            return;
        }
        try {
            if (root instanceof ViewGroup) {
                ViewGroup viewGroup = (ViewGroup) root;
                for (int i = 0; i < viewGroup.getChildCount(); i++) {
                    applyFont(context, viewGroup.getChildAt(i), fontName);
                }
            } else if (root instanceof TextView) {
                if (typeface == null) {
                    setTypeface(context, fontName);
                }
                ((TextView) root).setTypeface(typeface);
            } else if (root instanceof TextSwitcher) {
                TextSwitcher textSwitcher = (TextSwitcher) root;
                for (int i = 0; i < textSwitcher.getChildCount(); i++) {
                    TextView textView = (TextView) textSwitcher.getChildAt(i);
                    textView.setTypeface(typeface);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置要使用的字体
     *
     * @param context
     * @param fontName
     */
    public static void setTypeface(Context context, String fontName) {
        fontName = "fonts/" + fontName;
        if (FONT_NAME == null) {
            return;
        }
        if (typeface == null) {
            if (TextUtils.isEmpty(fontName)) {
                fontName = "fonts/" + FONT_NAME;
            }
            typeface = Typeface.createFromAsset(context.getAssets(), fontName);
        }
    }

}
